import React, { useState } from 'react';
import { Form, InputNumber, Card, Select, Button, Row, Col, message } from 'antd';
import { SettingOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';

import { setcalibrate } from "@/api/sensor";
import { getState } from "@/api/common";
import { LED_OPTIONS } from '@/utils/constants';
import "./index.scss";

function Sensor() {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  
  // 提取重复的卡片标题渲染
  const renderCardTitle = (icon, titleKey) => (
    <div className='title'>
      {icon}
      <span className="tit">{t(titleKey)}</span>
    </div>
  );

  function onFinish(values) {
    getState().then(res => {
      if (res[0].state == 'on') {
        message.info(t('message.pod'))
      } else {
        setcalibrate(values).then(res => {
          message.success(t('message.test.sent'));
        })
      }
    });
  }

  return (
    <div className="sensor-container">
      <div className="row-a1">
        <div className="con-a1">
          <Card title={renderCardTitle(<SettingOutlined style={{ color: '#08c' }} />, 'sensor.sensorThreshold')}>
            <div className="con-a1">
              <Form
                form={form}
                layout="vertical"
                autoComplete="off"
                onFinish={onFinish}
                initialValues={{
                  addr: 'A1',
                  threshold: 1
                }}
              >
                <Row>
                  <Col span={12}>
                    <Form.Item
                      label={t('sensor.address')}
                      name="addr"
                      rules={[{ required: true, message: t('sensor.addressTips') }]}
                    >
                      <Select options={LED_OPTIONS} />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label={t('sensor.threshold')}
                      name="threshold"
                      rules={[{ required: true, message: t('sensor.thresholdTips') }]}
                    >
                      <InputNumber min={1} max={100} />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item>
                      <div className="btns">
                        <Button className='submit-btn btn' type="primary" htmlType="submit">
                          {t('sensor.applyToSelected')}
                        </Button>
                      </div>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </div>
          </Card>
        </div>
      </div>
    </div>
  )
}

export default Sensor;